package com.lichuang.fruitvarietysm.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lichuang.fruitvarietysm.manage.entity.User;
import com.lichuang.fruitvarietysm.manage.enums.UserRole;
import com.lichuang.fruitvarietysm.manage.mapper.UserMapper;
import com.lichuang.fruitvarietysm.manage.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author shuaihang
 * @since 2019-07-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public User queryAdminUser(User user) {
        user.setUserRole(UserRole.ADMIN.getValue());
        QueryWrapper queryWrapper = new QueryWrapper(user);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public void saveUserWithRedis(User user, HttpServletResponse response) {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String key = "user::" + token;
        // 超时时间
        long timeOut = 3;
        // 将token存入redis
        redisTemplate.opsForValue().set(key, user, Duration.ofDays(timeOut));
        Cookie cookie = new Cookie("loginToken", token);
        // 设置cookie的过期时间为3天
        cookie.setMaxAge(259200);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
